﻿/**
<code>
  <author name="Zealic" email="zealic(at)gmail.com" type="Creator"/>
</code>
**/
using System;


namespace Zealib.Template
{
    public static class ExpressionValidation
    {
        public static bool IsNonEmpty(string expression)
        {
            return expression.Length != 0;
        }

        public static bool IsVariableName(string expression)
        {
            if (expression.Length == 0)
                return false;

            char first = expression[0];
            if (expression.Length > 255 ||
                char.IsDigit(first))
                return false;

            for (int i = 1; i < expression.Length; i++)
            {
                char c = expression[i];
                if (!(char.IsLetter(c) || char.IsNumber(c)))
                    return false;
            }
            return true;
        }

        public static bool IsLetter(string expression)
        {
            for (int i = 0; i < expression.Length; i++)
                if (!char.IsLetter(expression[i]))
                    return false;
            return true;
        }

        public static bool IsNumber(string expression)
        {
            for (int i = 0; i < expression.Length; i++)
                if (!char.IsNumber(expression[i]))
                    return false;
            return true;
        }

        public static bool IsMemberAccess(string expression)
        {
            string[] segments = expression.Split('.');
            foreach (string segment in segments)
            {
                if (!IsVariableName(segment))
                    return false;
            }
            return true;
        }

        public static bool ExistNamespace(string expression)
        {
            string ns;
            return ExistNamespace(expression, out ns);
        }

        public static bool ExistNamespace(string expression, out string ns)
        {
            ns = null;
            int index = expression.IndexOf(':');
            if (index < 1) return false;
            ns = expression.Substring(0, index);
            return IsVariableName(ns);
        }

    }
}
